<template>
  <div class="reports-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <div class="header-title">
            <h1>🚨 举报管理</h1>
            <p>处理用户举报的内容，维护社区环境</p>
          </div>
        </div>
        <div class="header-stats">
          <div class="stat-item">
            <div class="stat-number">{{ total }}</div>
            <div class="stat-label">总举报数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ reports.filter(r => r.status === 0).length }}</div>
            <div class="stat-label">待处理</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-form :model="filters" :inline="true" class="filter-form">
        <el-form-item label="状态">
          <el-select
            v-model="filters.status"
            placeholder="选择状态"
            clearable
            @change="handleSearch"
            style="width: 140px"
          >
            <el-option label="全部" value="" />
            <el-option label="待处理" :value="0" />
            <el-option label="已处理" :value="1" />
            <el-option label="已驳回" :value="2" />
            <el-option label="已删除内容" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="目标类型">
          <el-select
            v-model="filters.targetType"
            placeholder="选择目标类型"
            clearable
            @change="handleSearch"
            style="width: 140px"
          >
            <el-option label="全部" value="" />
            <el-option label="帖子" :value="1" />
            <el-option label="评论" :value="2" />
            <el-option label="用户" :value="3" />
            <el-option label="悄悄话" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="举报类型">
          <el-select
            v-model="filters.reasonType"
            placeholder="选择举报类型"
            clearable
            @change="handleSearch"
            style="width: 140px"
          >
            <el-option label="全部" value="" />
            <el-option label="垃圾信息" :value="1" />
            <el-option label="违法违规" :value="2" />
            <el-option label="涉黄涉暴" :value="3" />
            <el-option label="恶意骚扰" :value="4" />
            <el-option label="其他" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" size="default">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetFilters" size="default">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 当前筛选条件显示 -->
      <div class="active-filters" v-if="hasActiveFilters">
        <div class="filters-title">
          <el-icon><Discount /></el-icon>
          <span>当前筛选条件：</span>
        </div>
        <div class="filter-tags">
          <el-tag
            v-if="filters.status !== ''"
            type="primary"
            closable
            @close="
              filters.status = '';
              handleSearch();
            "
          >
            状态：{{ getStatusText(filters.status) }}
          </el-tag>
          <el-tag
            v-if="filters.targetType !== ''"
            type="success"
            closable
            @close="
              filters.targetType = '';
              handleSearch();
            "
          >
            目标类型：{{ getTargetTypeText(filters.targetType) }}
          </el-tag>
          <el-tag
            v-if="filters.reasonType !== ''"
            type="warning"
            closable
            @close="
              filters.reasonType = '';
              handleSearch();
            "
          >
            举报类型：{{ getReasonTypeText(filters.reasonType) }}
          </el-tag>
          <el-button size="small" type="info" text @click="resetFilters">
            <el-icon><Close /></el-icon>
            清除所有筛选
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 举报列表 -->
    <el-card class="reports-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon><List /></el-icon>
            <span>举报列表</span>
            <el-tag type="info" size="small">共 {{ total }} 条</el-tag>
          </div>
          <el-button type="primary" @click="loadReports" :loading="loading" size="default">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </div>
      </template>

      <el-table :data="reports" v-loading="loading" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="举报者" width="120">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :src="row.reporter?.avatar" :size="32">
                {{ row.reporter?.username?.charAt(0) }}
              </el-avatar>
              <span>{{ row.reporter?.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="目标类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTargetTypeTagType(row.targetType)" effect="light">
              {{ row.targetTypeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="目标内容" min-width="200">
          <template #default="{ row }">
            <div class="target-content">
              <div class="target-title">{{ row.targetContent?.title || "未知内容" }}</div>
              <div class="target-author" v-if="row.targetContent?.authorName">
                作者: {{ row.targetContent.authorName }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="举报原因" width="120">
          <template #default="{ row }">
            <el-tag :type="getReasonTypeTagType(row.reasonType)" effect="light">
              {{ row.reasonTypeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" effect="light">
              {{ row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetail(row)" type="info" plain>
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button
              v-if="row.status === 0"
              type="primary"
              size="small"
              @click="handleReport(row)"
            >
              <el-icon><Edit /></el-icon>
              处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 举报详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="举报详情" width="800px" class="detail-dialog">
      <div v-if="selectedReport" class="report-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="举报ID">{{ selectedReport.id }}</el-descriptions-item>
          <el-descriptions-item label="举报者">
            <div class="user-info">
              <el-avatar :src="selectedReport.reporter?.avatar" :size="24">
                {{ selectedReport.reporter?.username?.charAt(0) }}
              </el-avatar>
              <span>{{ selectedReport.reporter?.username }}</span>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="目标类型">
            <el-tag :type="getTargetTypeTagType(selectedReport.targetType)">
              {{ selectedReport.targetTypeName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="举报原因">
            <el-tag :type="getReasonTypeTagType(selectedReport.reasonType)">
              {{ selectedReport.reasonTypeName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(selectedReport.status)">
              {{ selectedReport.statusName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatTime(selectedReport.createTime) }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="detail-section">
          <h4>详细描述</h4>
          <p>{{ selectedReport.reasonDetail || "无详细描述" }}</p>
        </div>

        <div class="detail-section" v-if="selectedReport.targetContent">
          <h4>目标内容</h4>
          <div class="target-detail">
            <p><strong>标题:</strong> {{ selectedReport.targetContent.title }}</p>
            <p v-if="selectedReport.targetContent.content">
              <strong>内容:</strong> {{ selectedReport.targetContent.content }}
            </p>
            <p v-if="selectedReport.targetContent.authorName">
              <strong>作者:</strong> {{ selectedReport.targetContent.authorName }}
            </p>
            <p>
              <strong>状态:</strong>
              <el-tag :type="selectedReport.targetContent.exists ? 'success' : 'danger'">
                {{ selectedReport.targetContent.exists ? "存在" : "已删除" }}
              </el-tag>
            </p>
          </div>
        </div>

        <div class="detail-section" v-if="selectedReport.handleResult">
          <h4>处理结果</h4>
          <p>{{ selectedReport.handleResult }}</p>
          <p v-if="selectedReport.handler">
            <strong>处理人:</strong> {{ selectedReport.handler.username }}
          </p>
          <p v-if="selectedReport.handleTime">
            <strong>处理时间:</strong> {{ formatTime(selectedReport.handleTime) }}
          </p>
        </div>
      </div>
    </el-dialog>

    <!-- 处理举报对话框 -->
    <el-dialog v-model="showHandleDialog" title="处理举报" width="600px" class="handle-dialog">
      <el-form :model="handleForm" :rules="handleRules" ref="handleFormRef" label-width="100px">
        <el-form-item label="处理结果" prop="status">
          <el-radio-group v-model="handleForm.status">
            <el-radio :label="1">通过（举报有效）</el-radio>
            <el-radio :label="2">驳回（举报无效）</el-radio>
            <el-radio :label="3">删除内容</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理说明" prop="handleResult">
          <el-input
            v-model="handleForm.handleResult"
            type="textarea"
            :rows="4"
            placeholder="请填写处理说明..."
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item v-if="handleForm.status === 3">
          <el-checkbox v-model="handleForm.deleteTargetContent"> 同时删除目标内容 </el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showHandleDialog = false">取消</el-button>
          <el-button type="primary" @click="submitHandle" :loading="handling"> 确认处理 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Search, Refresh, Close, List, View, Edit, Discount } from "@element-plus/icons-vue";
import {
  getReports,
  handleReport as handleReportAPI,
  type ReportDTO,
  type ReportHandleRequest,
} from "@/api/report";

// 响应式数据
const loading = ref(false);
const handling = ref(false);
const reports = ref<ReportDTO[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(20);

const showDetailDialog = ref(false);
const showHandleDialog = ref(false);
const selectedReport = ref<ReportDTO | null>(null);
const handleFormRef = ref<FormInstance>();

// 筛选条件
const filters = reactive({
  status: "" as string | number,
  targetType: "" as string | number,
  reasonType: "" as string | number,
});

// 处理表单
const handleForm = reactive({
  status: 1,
  handleResult: "",
  deleteTargetContent: false,
});

const handleRules = {
  status: [{ required: true, message: "请选择处理结果", trigger: "change" }],
  handleResult: [
    { required: true, message: "请填写处理说明", trigger: "blur" },
    { min: 10, message: "处理说明至少需要10个字符", trigger: "blur" },
  ],
};

// 计算属性：是否有活跃的筛选条件
const hasActiveFilters = computed(() => {
  return filters.status !== "" || filters.targetType !== "" || filters.reasonType !== "";
});

// 获取筛选条件文本
const getStatusText = (status: string | number) => {
  const statusMap: Record<string, string> = {
    "0": "待处理",
    "1": "已处理",
    "2": "已驳回",
    "3": "已删除内容",
  };
  return statusMap[String(status)] || "";
};

const getTargetTypeText = (type: string | number) => {
  const typeMap: Record<string, string> = {
    "1": "帖子",
    "2": "评论",
    "3": "用户",
    "4": "悄悄话",
  };
  return typeMap[String(type)] || "";
};

const getReasonTypeText = (type: string | number) => {
  const typeMap: Record<string, string> = {
    "1": "垃圾信息",
    "2": "违法违规",
    "3": "涉黄涉暴",
    "4": "恶意骚扰",
    "5": "其他",
  };
  return typeMap[String(type)] || "";
};

// 加载举报列表
const loadReports = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      status: filters.status === "" ? undefined : Number(filters.status),
      targetType: filters.targetType === "" ? undefined : Number(filters.targetType),
      reasonType: filters.reasonType === "" ? undefined : Number(filters.reasonType),
    };

    const response = await getReports(params);
    reports.value = response.items;
    total.value = response.total;
  } catch (error) {
    console.error("Failed to load reports:", error);
    ElMessage.error("加载举报列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadReports();
};

// 重置筛选
const resetFilters = () => {
  filters.status = "";
  filters.targetType = "";
  filters.reasonType = "";
  handleSearch();
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  loadReports();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadReports();
};

// 查看详情
const viewDetail = (report: ReportDTO) => {
  selectedReport.value = report;
  showDetailDialog.value = true;
};

// 处理举报
const handleReport = (report: ReportDTO) => {
  selectedReport.value = report;
  handleForm.status = 1;
  handleForm.handleResult = "";
  handleForm.deleteTargetContent = false;
  showHandleDialog.value = true;
};

// 提交处理
const submitHandle = async () => {
  if (!handleFormRef.value || !selectedReport.value) return;

  try {
    await handleFormRef.value.validate();

    handling.value = true;

    const data: ReportHandleRequest = {
      status: handleForm.status,
      handleResult: handleForm.handleResult,
      deleteTargetContent: handleForm.status === 3 ? handleForm.deleteTargetContent : false,
    };

    await handleReportAPI(selectedReport.value.id, data);

    ElMessage.success("举报处理成功");
    showHandleDialog.value = false;
    loadReports(); // 重新加载列表
  } catch (error: any) {
    console.error("Failed to handle report:", error);
    ElMessage.error(error.message || "处理失败");
  } finally {
    handling.value = false;
  }
};

// 获取目标类型标签样式
const getTargetTypeTagType = (type: number) => {
  const typeMap: Record<number, string> = {
    1: "primary", // 帖子
    2: "success", // 评论
    3: "warning", // 用户
    4: "info", // 悄悄话
  };
  return typeMap[type] || "";
};

// 获取举报原因标签样式
const getReasonTypeTagType = (type: number) => {
  const typeMap: Record<number, string> = {
    1: "info", // 垃圾信息
    2: "danger", // 违法违规
    3: "danger", // 涉黄涉暴
    4: "warning", // 恶意骚扰
    5: "info", // 其他
  };
  return typeMap[type] || "";
};

// 获取状态标签样式
const getStatusTagType = (status: number) => {
  const statusMap: Record<number, string> = {
    0: "warning", // 待处理
    1: "success", // 已处理
    2: "info", // 已驳回
    3: "danger", // 已删除内容
  };
  return statusMap[status] || "";
};

// 格式化时间
const formatTime = (time: string) => {
  return new Date(time).toLocaleString();
};

// 组件挂载
onMounted(() => {
  loadReports();
});
</script>

<style scoped lang="scss">
.reports-view {
  .page-header {
    margin-bottom: 24px;
    background-color: #f5f7fa;
    padding: 20px 24px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .header-left {
      .header-title {
        h1 {
          margin: 0 0 8px 0;
          font-size: 24px;
          color: #2c3e50;
        }

        p {
          margin: 0;
          color: #666;
        }
      }
    }

    .header-stats {
      display: flex;
      gap: 20px;

      .stat-item {
        text-align: center;

        .stat-number {
          font-size: 24px;
          font-weight: bold;
          color: #409eff;
          margin-bottom: 4px;
        }

        .stat-label {
          font-size: 14px;
          color: #666;
        }
      }
    }
  }

  .filter-card {
    margin-bottom: 24px;

    .filter-header {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 600;
      color: #2c3e50;
      margin-bottom: 16px;
    }

    .filter-form {
      margin-bottom: 0;
    }

    .active-filters {
      margin-top: 16px;
      padding: 12px 16px;
      background-color: #f5f7fa;
      border-radius: 8px;
      border: 1px solid #e4e7ed;

      .filters-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 12px;
        color: #2c3e50;
        font-size: 14px;
      }

      .filter-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;

        .el-tag {
          .el-icon {
            margin-right: 4px;
          }
        }
      }
    }
  }

  .reports-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
      color: #2c3e50;

      .header-left {
        display: flex;
        align-items: center;
        gap: 12px;

        .el-icon {
          font-size: 18px;
          color: #409eff;
        }

        span {
          font-size: 16px;
        }

        .el-tag {
          margin-left: 8px;
        }
      }
    }

    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;

      span {
        font-size: 14px;
      }
    }

    .target-content {
      .target-title {
        font-weight: 500;
        color: #2c3e50;
        margin-bottom: 4px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .target-author {
        font-size: 12px;
        color: #666;
      }
    }

    .pagination-wrapper {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }

  .report-detail {
    .detail-section {
      margin-top: 24px;

      h4 {
        margin: 0 0 12px 0;
        color: #2c3e50;
        font-size: 16px;
      }

      p {
        margin: 0 0 8px 0;
        line-height: 1.6;
        color: #666;
      }

      .target-detail {
        background: #f5f7fa;
        padding: 16px;
        border-radius: 8px;
        border: 1px solid #e4e7ed;

        p {
          margin-bottom: 8px;

          &:last-child {
            margin-bottom: 0;
          }

          strong {
            color: #2c3e50;
          }
        }
      }
    }
  }

  .dialog-footer {
    text-align: right;
  }

  .detail-dialog,
  .handle-dialog {
    .el-dialog__header {
      background-color: #f5f7fa;
      border-bottom: 1px solid #e4e7ed;
    }

    .el-dialog__body {
      padding: 20px 24px;
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    .page-header {
      padding: 16px;

      .header-content {
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;
      }

      .header-stats {
        width: 100%;
        justify-content: space-around;
      }
    }

    .filter-card {
      .filter-form {
        .el-form-item {
          width: 100%;
          margin-bottom: 16px;

          .el-select,
          .el-button {
            width: 100%;
          }
        }
      }

      .active-filters {
        .filter-tags {
          flex-direction: column;
          gap: 8px;

          .el-tag,
          .el-button {
            width: fit-content;
          }
        }
      }
    }

    .reports-card {
      .card-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;

        .header-left {
          flex-wrap: wrap;
        }
      }
    }
  }
}
</style>
